package by.kniazhych.core.controllers {
	
	/**
	 * ...
	 * @author Boutylin Mikhail
	 */
	
	import by.kniazhych.core.data.ApplicationDataBase;
	import by.kniazhych.core.events.ApplicationEvent;
	import by.kniazhych.core.frames.ApplicationFrame;
	import by.kniazhych.core.frames.FrameBuilder;
	import by.kniazhych.core.view.frames.MenuFrame;
	import by.vaukalak.core.controllers.BaseController;
	import by.vaukalak.core.data.DataBase;
	import design.SoundButton;
	import flash.display.DisplayObjectContainer;
	import flash.display.MovieClip;
	import flash.events.MouseEvent;
	import flash.utils.Dictionary;
	
	[Frame(factoryClass="by.kniazhych.core.application.KniazhychFactory")]
	
	public class ApplicationController extends BaseController{
		
		//--------------------------------------------------------------------------
		//
		//  PROPERTIES
		//
		//--------------------------------------------------------------------------
		
		private const _frames:Dictionary = new Dictionary();
		private var _currentFrame:BaseFrameController;
		private var _frameBuilder:FrameBuilder;
		
		//--------------------------------------------------------------------------
		//
		//  CONSTRUCTOR
		//
		//--------------------------------------------------------------------------
		
		public function ApplicationController(container:DisplayObjectContainer) {
			super(container, new ApplicationDataBase());
			_frameBuilder = new FrameBuilder(this);
			_getFrame(ApplicationFrame.MENU);
			ApplicationDataBase(dataBase).addEventListener(ApplicationEvent.FRAME_CHANGED, _onFrameChanged);
			
			var soundButton:MovieClip = new SoundButton();
			soundButton.x = 380;
			soundButton.y = 515;
			container.addChild(soundButton);
			soundButton.addEventListener(MouseEvent.CLICK, _onSoundButtonClick);
		}
		
		private function _onSoundButtonClick(e:MouseEvent):void {
			ApplicationDataBase(dataBase).togleSound();
			MovieClip(e.currentTarget).gotoAndStop(ApplicationDataBase(dataBase).soundIsPlaying ? 1 : 2);
		}
		
		private function _onFrameChanged(e:ApplicationEvent):void {
			_getFrame(e.frameToNavigate);
		}
		
		private function _getFrame(frameName:String):void {
			if (_currentFrame) _currentFrame.exitFrame();
			_currentFrame = BaseFrameController(_frames[frameName] ? _frames[frameName] : _frameBuilder.buildFrame(frameName));
			_currentFrame.enterFrame();
			_frames[frameName] = _currentFrame;
		}
		
	}

}